package com.cvte.sunkit.manage

import android.annotation.SuppressLint
import android.content.Context
import android.os.DropBoxManager
import android.util.Log
import com.cvte.sunkit.App
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date

/**
 *  @PackageName com.cvte.sunkit.utils
 *  @Description 对dropbox记录的日志信息
 *  @Author lixu
 *  @Data 2023/7/26 15:06
 *  @Version 1.0
 */
class DropboxLogcatManager private constructor() {
    private var mCrashCnt = 0
    private var mAnrCnt = 0

    companion object {
        @Volatile
        private var sInstance: DropboxLogcatManager? = null
        private val TAG = DropboxLogcatManager::class.java.simpleName
        val instance: DropboxLogcatManager?
            get() {
                if (sInstance == null) {
                    synchronized(DropboxLogcatManager::class.java) {
                        if (sInstance == null) {
                            sInstance = DropboxLogcatManager()
                        }
                    }
                }
                return sInstance
            }
    }

    fun output(pathname: String, time: Long, maxBytes: Int): String? {
        val dropBoxManager =
            App.mInstance.getSystemService(Context.DROPBOX_SERVICE) as DropBoxManager // 1、获取 dropbox manager
        var file = File(pathname)
        if (file.isDirectory) file = File(pathname, "dropbox.log")
        if (file.exists()) {
            file.delete()
        }
        file.parentFile?.mkdirs()
        try {
            if (!file.createNewFile()) {
                Log.e(TAG, "create file " + file.absolutePath + " failed")
                return null
            }
        } catch (e: IOException) {
            Log.e(TAG, e.message!!)
            return null
        }
        try {
            BufferedWriter(FileWriter(file.absolutePath, true)).use { writer ->
                var startTime = time

                var entry: DropBoxManager.Entry?
                mCrashCnt = 0
                mAnrCnt = 0
                while (dropBoxManager.getNextEntry(null, startTime)
                        .also { entry = it } != null
                ) { // 2、获取所有的dropbox信息
                    writer.write(
                        """
    异常发生时间：${shiftTimeFormat(entry!!.timeMillis)}
    异常类型：${entry!!.tag}:
    详细信息：${entry!!.getText(maxBytes)}
    
    
    """.trimIndent()
                    ) // 3、写入文件
                    if (entry!!.tag == "system_app_crash" || entry!!.tag == "data_app_crash") {
                        mCrashCnt++
                    }
                    if (entry!!.tag == "anr") {
                        mAnrCnt++
                    }
                    startTime = entry!!.timeMillis // 4、reset startTime for the next entry
                    entry!!.close() // 5、don’t forget to close the entry after you finished your task
                }
            }
        } catch (e: IOException) {
            Log.e(TAG, e.message!!)
        }
        return file.absolutePath
    }

    @SuppressLint("SimpleDateFormat")
    private fun shiftTimeFormat(currentTime: Long): String {
        val date = Date(currentTime)
        val pattern = "yyyy年MM月dd日HH时mm分ss秒"
        val sdf = SimpleDateFormat(pattern)
        val formattedDateTime = sdf.format(date)
        return formattedDateTime.toString()
    }

    fun getCrashCnt() = mCrashCnt
    fun getAnrCnt() = mAnrCnt

}